package nio;

import org.junit.Test;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class BufferTest {
    @Test
    public void test1(){
        CharBuffer buffer = CharBuffer.allocate(10);
        print("初始化后",buffer);

        buffer.put("abcd".toCharArray());
        print("put数据后",buffer);

        buffer.flip();
        print("flip后",buffer);

        buffer.get();
        print("get后",buffer);

        //buffer.compact();
        buffer.clear();
        print("clear后",buffer);
    }

    @Test
    public void test2(){
        ByteBuffer buffer = ByteBuffer.allocateDirect(10);

        print("初始化后",buffer);

        buffer.put("abcd".getBytes());
        print("put数据后",buffer);

        buffer.flip();
        print("flip后",buffer);

        buffer.get();
        print("get后",buffer);
        //buffer.compact();
        buffer.clear();
        print("clear后",buffer);

    }


    private void print(String name,Buffer buffer) {
        System.out.println(name+"--->position = "+buffer.position()+"; "+"limit = "+buffer.limit()+"; "+"capacity = "+buffer.capacity()+"; ");
    }
}
